-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.cpp
More file actions
37 lines (30 loc) · 739 Bytes
/
Solution.cpp
File metadata and controls
37 lines (30 loc) · 739 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <vector>
using namespace std;
void moveZerosToEnd(vector<int>& arr) {
int j = 0; // Points to the next position for a non-zero element
// Traverse the array
for (int i = 0; i < arr.size(); i++) {
if (arr[i] != 0) {
swap(arr[i], arr[j]);
j++;
}
}
}
int main() {
int n;
cout << "Enter the size of the array: ";
cin >> n;
vector<int> arr(n);
cout << "Enter " << n << " elements of the array: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
moveZerosToEnd(arr);
cout << "Array after moving zeros to the end: ";
for (int num : arr) {
cout << num << " ";
}
cout << endl;
return 0;
}